package com.lagou.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Kirito
 * @description:
 * @date 2020/04/24
 */
public class StaticResourceUtil {

    private StaticResourceUtil() {
        throw new RuntimeException("Can not be instantiated");
    }

    /**
     * 获取资源文件的绝对路径
     *
     * @param url String
     * @return String
     */
    public static String getAbsolutePath(String url) {
        // 获取当前的classpath路径，因为静态资源文件一般存放在classpath下
        String basePath = StaticResourceUtil.class.getResource("/").getPath();
        // 将文件分隔符替换成浏览器分隔符，前面两个'\\'代表转义，后面两个代表windows的文件分隔符
        return basePath.replaceAll("\\\\", "/") + url;
    }

    /**
     * 通过IO输出静态资源文件
     *
     * @param file         File
     * @param outputStream OutputStream
     */
    public static void outputStaticResource(File file, OutputStream outputStream) throws IOException {
        InputStream inputStream = new FileInputStream(file);
        long length = 0L;
        while (length == 0) {
            length = inputStream.available();
        }
        // 先输出Http请求头信息
        outputStream.write(HttpProtocolUtil.getHttpHeader200(length).getBytes());

        // 已输出的长度
        long written = 0L;
        // 一次读取的长度
        int readSize = 1024;
        byte[] bytes = new byte[readSize];

        // 如果已输出的小于总的数据长度
        while (written < length) {
            // 判断是不是最后一次读取，也就是 已输出的+每次读取的长度>总长度
            if (written + readSize > length) {
                readSize = (int) (length - written);
                bytes = new byte[readSize];
            }

            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            written += written;
        }

        // 关闭资源
        inputStream.close();
        outputStream.close();
    }
}
